package dnl.toolbox.lang;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import dnl.toolbox.time.TimeRange;

public class StringConversions {
	private static List<DateFormat> dateFormats = new ArrayList<DateFormat>();

	static {
		dateFormats.add(new SimpleDateFormat("dd.MM.yyyy"));
		dateFormats.add(new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"));
	}

	private static Date parseDate(String s) {
		for (DateFormat df : dateFormats) {
			try {
				Date date = df.parse(s);
				return date;
			} catch (java.text.ParseException e) {
			}
		}
		return null;
	}

	public static Date getDate(String s) {
		if (s == null) {
			return null;
		}
		Date date = parseDate(s);
		if (date != null) {
			return date;
		}
		throw new IllegalArgumentException("The given date cannot be parsed: " + s);
	}

	public static File getDir(String s) {
		File d = getFile(s);
		if (!d.isDirectory()) {
			throw new IllegalArgumentException("The given arg is not a directory: "
					+ d.getAbsolutePath());
		}
		return d;
	}

	public static File getFile(String s) {
		if (s == null) {
			return null;
		}
		File f = new File(s);
		return f;
	}

	public static TimeRange getTimeRange(String s) {
		if (s == null) {
			return null;
		}
		int countMatches = StringUtils.countMatches(s, "-");
		if (countMatches != 1) {
			throw new IllegalArgumentException("Time range separator is '-'. You entered: " + s);
		}
		String[] splits = StringUtils.split(s, "-");
		Date d1 = parseDate(splits[0]);
		Date d2 = parseDate(splits[1]);
		if (d1 == null || d2 == null) {
			throw new IllegalArgumentException("The given time range cannot be parsed: " + s);
		}
		return new TimeRange(d1, d2);
	}

	public static Integer getInteger(String s) {
		if (s == null) {
			return null;
		}
		return Integer.parseInt(s);
	}

	public static Boolean getBoolean(String s) {
		if (s == null) {
			return null;
		}
		if ("true".equals(s.toLowerCase())) {
			return Boolean.TRUE;
		}
		if ("false".equals(s.toLowerCase())) {
			return Boolean.FALSE;
		}
		throw new IllegalArgumentException("The given string cannot be parsed into a boolean: " + s);
	}
}
